package com.sjf.day02.Stack;

import java.util.Scanner;

/**
 *  链表实现栈
 *
 * @author <huangtang>
 * @since 2021/12/23 9:53
 **/
public class LinkedListStackDemo {

    public static void main(String[] args) {
        LinkedListStack stack = new LinkedListStack();
        String key="";
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while(loop){
            System.out.print("s:显示栈 \t");
            System.out.print("e:退出程序 \t");
            System.out.print("p:添加数据到栈中 \t");
            System.out.print("g:从栈中取出数据 \n");
            System.out.print("请输入: ");
            key = scanner.next();
            switch (key){
                case "s" :
                    try {
                        stack.list();
                        System.out.println();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case "p":
                    System.out.println("请输入一个数");
                    stack.push(new Node(scanner.nextInt()));
                    break;
                case "e":
                    System.out.println("退出程序");
                    loop=false;
                    break;
                case "g":
                    System.out.println("取出的数为"+stack.pop());
                default:
                    break;
            }
        }
    }

}

class LinkedListStack{
    private Node head = new Node(-1); //初始化一个头节点

    /**
     * 入栈
     * 每次入栈的节点直接放在head节点之后即可
     * @param node
     */
    public void push(Node node){
        Node tmp = head;
        node.next = tmp.next;
        tmp.next = node;
    }

    /**
     * 出栈
     * 每次出栈都出head节点的下一个节点
     * @return
     */
    public int pop(){
        Node tmp = head;
        int val = tmp.next.val;
        tmp.next = tmp.next.next;
        return val;
    }

    /**
     * 打印栈
     */
    public void list(){
        if(isEmpty()){
            throw new RuntimeException("栈为空");
        }
        Node tmp = head;
        while(tmp.next!=null){
            System.out.print(tmp.next.val+"->");
            tmp = tmp.next;
        }
    }
    public boolean isEmpty(){
        return head.next == null;
    }
}

class Node{
    public int val;
    public Node next;

    public Node(int val) {
        this.val = val;
    }
}